package com.lxw.rmg.menu.utils;

import java.lang.reflect.Field;
public class CompareUtils {
    /**
     * 对比两个对象的同名数字属性值的差值
     *
     * @param obj1 对象1
     * @param obj2 对象2
     * @return 返回一个字符串，表示不同的属性名和属性差值
     * @throws IllegalAccessException
     */
    public static String compareNumberFields(Object obj1, Object obj2) throws IllegalAccessException {
        Class clazz = obj1.getClass();
        Field[] fields = clazz.getDeclaredFields();
        StringBuilder stringBuilder = new StringBuilder();
        for (Field field : fields) {
            field.setAccessible(true);
            Object value1 = field.get(obj1);
            Object value2 = field.get(obj2);
            if (value1 == null && value2 == null) {
                continue;
            }
            if (value1 instanceof Number && value2 instanceof Number) {
                double num1 = ((Number) value1).doubleValue();
                double num2 = ((Number) value2).doubleValue();
                if (num1 != num2) {
                    String fieldName = field.getName();
                    stringBuilder.append(fieldName).append(":")
                            .append(num1 - num2).append(";");
                }
            }
        }
        return stringBuilder.toString();
    }
}